package com.projectfixit.web;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.lang.StringUtils;


import com.projectfixit.dao.FixitDao;
import com.projectfixit.entity.ContentDO;


@SuppressWarnings("serial")
public class FixitServlet extends HttpServlet {
	
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int result = processRequest(request);
		
		String responseJSON = "{\"success\":\"false\"}";
		response.setContentType("application/json");
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		if(result == 0){
			responseJSON = "{\"success\":\"true\"}";
		}
		response.getWriter().println(responseJSON);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int result = processRequest(request);
		
		String responseJSON = "{\"success\":\"false\"}";
		response.setContentType("application/json");
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		if(result == 0){
			responseJSON = "{\"success\":\"true\"}";
		}
		response.getWriter().println(responseJSON);

	}

	protected int processRequest(HttpServletRequest request) {
		String content = request.getParameter("content");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String url = request.getParameter("url");
		String errorType = request.getParameter("errorType");
		String errorContent = request.getParameter("errorContent");
		String startOffset = request.getParameter("start_offset");
		String endOffset = request.getParameter("end_offset");
		
		int result = -1;
		result = insertErrorContent(content, title, author, url, result, errorType, errorContent);
		return result;
	}

	protected int insertErrorContent(String content, String title, String author,
			String url, int result, String errorType, String errorContent) {
		
		if (!StringUtils.isBlank(content) && 
				!StringUtils.isBlank(title) && 
				!StringUtils.isBlank(url) && 
				!StringUtils.isBlank(author) && 
				!StringUtils.isBlank(errorType) &&
				ContentDO.contentErrorType.contains(errorType.toUpperCase())){

			FixitDao fixitDao = new FixitDao();
			//There is no easy way to retrieve data with composite keys from google app engine. 
			result = fixitDao.putContent(content, title, author, url+"::"+errorType,  errorContent);
			
		}
		return result;
	}
	
	
}
